<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="原密码" prop="old_pwd" style="width: 350px">
        <el-input
          type="password"
          v-model="ruleForm.old_pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd" style="width: 350px">
        <el-input
          type="password"
          v-model="ruleForm.new_pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd" style="width: 350px">
        <el-input
          type="password"
          v-model="ruleForm.re_pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { pwdForm } from '../../api/art.js'
export default {
  data () {
    const checkNewPwd = (rule, value, cb) => {
      if (value === this.ruleForm.old_pwd) {
        return cb(new Error('新密码不能和原密码一致'))
      }
      cb()
    }
    // 检验两次新密码是否一致
    const checkSamePwd = (rule, value, cb) => {
      if (value !== this.ruleForm.new_pwd) {
        return cb(new Error('两次输入的密码不一致'))
      }
      cb()
    }
    return {
      ruleForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符串',
            trigger: 'blur'
          },
          { validator: checkNewPwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符串',
            trigger: 'blur'
          },
          {
            validator: checkSamePwd,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // alert('submit!')
          const res = await pwdForm(this.ruleForm)
          console.log(res)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
